package de.clue.corpus.twitter.transform;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Iterator;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.io.FileUtils;

/**
 * Class used to transform directory of files using xslt.
 * 
 * @author asuslova
 *
 */
public class XalanTransformDirectory {
    
    
    private final String inputPath;
    private final String outputPath;
    private final String xslPath;

    public XalanTransformDirectory(String inputPath, String outputPath, String xslPath){
        this.inputPath = inputPath;
        this.outputPath = outputPath;
        this.xslPath = xslPath;
        
    }
    
    public void process() throws Exception{
        transformfilesIndirectory();
    }

    private void transformfilesIndirectory() throws Exception {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(new StreamSource(xslPath));

        File directory = new File(inputPath);
        File outputDirectory = new File(outputPath);
        if(!outputDirectory.exists()){
            outputDirectory.mkdirs();
        }
        Collection<File> xmlFiles = FileUtils.listFiles(directory, new String[]{"xml"}, false);
        for (Iterator iterator = xmlFiles.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            System.out.println("Processing: " + file.getName());
            transformer.transform(new StreamSource(file), new StreamResult(new FileOutputStream(outputPath+"out_"+file.getName())));
            
        }
        System.out.println("FINISHED!");
        
        
    }

}
